package pers.vic.test.json.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.apache.commons.text.StringEscapeUtils;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.io.IOException;

/**
 * 描述:xss 转义 序列化时
 * @author Vic.xu
 * @date 2022-03-21 11:23
 */
public class XssStringJsonSerializer extends JsonSerializer<String> {
    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value != null) {

            String encodedValue = StringEscapeUtils.escapeHtml4(value);
            gen.writeString(encodedValue);
        }
    }

    public static void main(String[] args) throws JsonProcessingException {
        TestXss xss = new TestXss();
        xss.setId("<abc>");
        xss.setName("<script>");
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.writeValueAsString(xss));

        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        SimpleModule xssModule = new SimpleModule("XssStringJsonSerializer");
        xssModule.addSerializer(String.class, new XssStringJsonSerializer());
        objectMapper.registerModule(xssModule);
        System.out.println(objectMapper.writeValueAsString(xss));
    }
}


class TestXss {

    @JsonSerialize(using = XssStringJsonSerializer.class)
    private String id;

    String name;


    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
